<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        ref="pageFilter"
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            v-model="time"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD "
            type="daterange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
            @change="timeChange"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>

    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-print>
          <el-button
            v-if="$permission('purchaseSupplierSummary:printDetail')"
            @click="print"
            >打印</el-button
          >
        </template>
        <template v-slot:filter-excel>
          <el-button
            v-if="$permission('purchaseSupplierSummary:excelDetail')"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>
        <template v-slot:filter-excelAccountingDetailList>
          <el-button
            v-if="
              $permission('purchaseSupplierSummary:excelAccountingDetailList')
            "
            @click="exportExcelAccountingDetailList"
            >导出辅助核算明细</el-button
          >
        </template>
      </NewPageFilter>
    </div>
    <!-- 表格 -->
    <table-container
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="true"
      :summary-field-list="tableInfo.summaryFieldList"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      @handleEvent="handleEvent"
      @pageInfo="pageInfo"
    >
    </table-container>
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="purchaseSupplierSummary">
import {
  excelPurchaseSupplierSummary,
  printPurchaseSupplierSummary,
  getPurchaseSupplierSummaryPage,
  pzhpurchaseSupplierSummaryExcelAccountingDetailList,
} from '@/api/dataQuery.js'
import moment from 'moment'
import { fatchTemplateByCode } from '@/api/base'
import { getSupplierAll } from '@/api/core'
const { proxy } = getCurrentInstance()
const props = defineProps(['query'])

const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    supplierAuth: 'supplierId',
    operateTimeGreater: moment(
      new Date(new Date().getTime() - 3600 * 1000 * 24 * 30)
    ).format('YYYY-MM-DD'),
    operateTimeLesser: moment(new Date()).format('YYYY-MM-DD'),
    isCoreFiscalPeriodQuery: false,
  },
  searchList: [
    {
      label: '统计时间',
      slot: true,
      value: 'operateTime',
      event: search,
    },
    {
      label: '会计期间',
      value: 'fiscalPeriodName',
      asValue: 'coreFiscalPeriodId',
      componentType: 'select-fiscal-period',
      query: {
        fiscalType: 1,
      }, //1 = 物资 2 = 资产
      checkBox: false,
      highlightRow: true,
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: { supplierAuth: 'supplierId', sort: 'create_time desc' },
      clearable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      multiple: true,
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      value: 'print',
      type: 'slot',
    },
    {
      value: 'excel',
      type: 'slot',
    },
    {
      value: 'excelAccountingDetailList',
      type: 'slot',
    },
  ],
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const time = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 30)).format(
    'YYYY-MM-DD'
  ),
  moment(new Date()).format('YYYY-MM-DD'),
])

const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getPurchaseSupplierSummaryPage,
  selections: [],
  summaryFieldList: [
    { value: 'receiveAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'returnAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'amount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    { label: '编码', value: 'supplierCode' },
    { label: '供应商', value: 'supplierName' },
    {
      label: '采购入库',
      value: 'receiveAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '采购退货',
      value: 'returnAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '汇总',
      value: 'amount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
watch(
  () => filterInfo.value.query.coreFiscalPeriodId,
  (val) => {
    if (val) {
      filterInfo.value.query.operateTimeGreater = ''
      filterInfo.value.query.operateTimeLesser = ''
      time.value = []
    }
  }
)
watch(
  () => filterInfo.value.query.operateTimeGreater,
  (val) => {
    if (val) {
      proxy.$refs.pageFilter.clearFiscalPeriod()
    }
  }
)

onMounted(() => {
  getList()
})
function getList() {
  tableInfo.value.refresh = Math.random()
}

function search() {
  if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.operateTimeGreater
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (
    filterInfo.value.query.operateTimeGreater &&
    filterInfo.value.query.operateTimeLesser
  ) {
    filterInfo.value.query.isCoreFiscalPeriodQuery = false
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
    return
  } else {
    if (!filterInfo.value.query.coreFiscalPeriodId) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.coreFiscalPeriodId) {
    filterInfo.value.query.coreFiscalPeriodId = Number(
      filterInfo.value.query.coreFiscalPeriodId
    )
    filterInfo.value.query.isCoreFiscalPeriodQuery = true
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function exportExcel() {
  if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.operateTimeGreater
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (
    filterInfo.value.query.operateTimeGreater &&
    filterInfo.value.query.operateTimeLesser
  ) {
    filterInfo.value.query.isCoreFiscalPeriodQuery = false
    excelPurchaseSupplierSummary(
      proxy.$fn.delEmptyAttribute(filterInfo.value.query)
    ).then((resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    })
    return
  } else {
    if (!filterInfo.value.query.coreFiscalPeriodId) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.coreFiscalPeriodId) {
    filterInfo.value.query.coreFiscalPeriodId = Number(
      filterInfo.value.query.coreFiscalPeriodId
    )
    filterInfo.value.query.isCoreFiscalPeriodQuery = true
    excelPurchaseSupplierSummary(
      proxy.$fn.delEmptyAttribute(filterInfo.value.query)
    ).then((resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    })
  }
}
function pageInfo(obj) {
  page.value = obj
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcelAccountingDetailList() {
  if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.operateTimeGreater
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (
    filterInfo.value.query.operateTimeGreater &&
    filterInfo.value.query.operateTimeLesser
  ) {
    filterInfo.value.query.isCoreFiscalPeriodQuery = false
    dialogInfo.value.visible = true
    dialogInfo.value.type = 'excel'
    dialogInfo.value.msg = '请选择数据导出范围'
    dialogInfo.value.btList[1].label = '导出'
    dialogInfo.value.flag = 'page'
    return
  } else {
    if (!filterInfo.value.query.coreFiscalPeriodId) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.coreFiscalPeriodId) {
    filterInfo.value.query.coreFiscalPeriodId = Number(
      filterInfo.value.query.coreFiscalPeriodId
    )
    filterInfo.value.query.isCoreFiscalPeriodQuery = true
    dialogInfo.value.visible = true
    dialogInfo.value.type = 'excel'
    dialogInfo.value.msg = '请选择数据导出范围'
    dialogInfo.value.btList[1].label = '导出'
    dialogInfo.value.flag = 'page'
  }
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }
  pzhpurchaseSupplierSummaryExcelAccountingDetailList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.operateTimeGreater = val[0]
    filterInfo.value.query.operateTimeLesser = val[1]
    time.value = [val[0], val[1]]
  } else {
    filterInfo.value.query.operateTimeGreater = ''
    filterInfo.value.query.operateTimeLesser = ''
    time.value = []
  }
}
//打印
function print() {
  if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.operateTimeGreater
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (
    filterInfo.value.query.operateTimeGreater &&
    filterInfo.value.query.operateTimeLesser
  ) {
    filterInfo.value.query.isCoreFiscalPeriodQuery = false
    fatchTemplateByCode({
      resourceCode: 'purchaseSupplierSummary:printDetail',
      isDefault: 1,
    }).then((res) => {
      if (res && res.success) {
        let temp = proxy.$fn.getPrintTemp(res.data[0])
        getPrintData(temp)
      }
    })
    return
  } else {
    if (!filterInfo.value.query.coreFiscalPeriodId) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.coreFiscalPeriodId) {
    filterInfo.value.query.coreFiscalPeriodId = Number(
      filterInfo.value.query.coreFiscalPeriodId
    )
    filterInfo.value.query.isCoreFiscalPeriodQuery = true
    fatchTemplateByCode({
      resourceCode: 'purchaseSupplierSummary:printDetail',
      isDefault: 1,
    }).then((res) => {
      if (res && res.success) {
        let temp = proxy.$fn.getPrintTemp(res.data[0])
        getPrintData(temp)
      }
    })
  }
}
function getPrintData(temp) {
  printPurchaseSupplierSummary(filterInfo.value.query).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('purchaseSupplierSummary:price')
      )
    }
  })
}
</script>

<style scoped></style>
